package com.py.credit.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.py.credit.constant.ResourcePath;
import com.py.credit.dao.WebbgdzDao;
import com.py.credit.entity.Hcbg;
import com.py.credit.service.WebBgdzService;
import com.py.framework.core.exception.ServiceException;
@Service
public class WebBgdzServiceImpl implements WebBgdzService {

    @Autowired
    private WebbgdzDao webbgdzDao;

    /**
     * no:报告编号 productName：制作方 reportStatement：报告声明 waterMark：水印图片
     */
    @Override
    public void addHcbg(String watermark, String reportNo, String reportStatment, CommonsMultipartFile waterMark,
                        String reportProducer) throws IOException {

        if (waterMark != null) {

            BufferedImage image = ImageIO.read(waterMark.getInputStream());

            if (image != null) {

                int width = image.getWidth();

                int height = image.getHeight();

                if (width > 1080 || height > 1920) {

                    throw new ServiceException("水印图片图尺寸不超过1080*1920Px");

                }

            } else {

                throw new ServiceException("上传文件非图片,请重新上传");
            }

            if (!"image/png".equals(waterMark.getContentType()) && !"image/jpeg".equals(waterMark.getContentType())
                    && !"image/jpg".equals(waterMark.getContentType())) {

                throw new ServiceException("水印图片必须是JPG、JEPG、PNG 格式");
            }

            if (waterMark.getSize() > 512 * 1024) {

                throw new ServiceException("水印图片不能超过512k");

            }

            File dirPath = new File(watermark);

            if (!dirPath.exists()) {

                dirPath.mkdirs();

            }

            waterMark.transferTo(new File(watermark + ResourcePath.WATERMAERK_NAME));

        }

        Hcbg record = new Hcbg(reportNo, reportStatment,
                ResourcePath.WATERMAERK_IMAGES_DIR + ResourcePath.WATERMAERK_NAME, reportProducer);

        Hcbg selectLatest = webbgdzDao.selectLatest();

        if (selectLatest != null) {

            record.setId(selectLatest.getId());

            webbgdzDao.updateByPrimaryKeySelective(record);

        } else {

            webbgdzDao.upload(record);
        }

    }

    @Override
    public Hcbg getLatest() {

        return webbgdzDao.selectLatest();
    }

}
